<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" scroll :max-height="500">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入用户姓名" class="!w-240px" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入用户昵称" class="!w-240px" />
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" class="!w-240px" />
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <!-- <el-date-picker
          v-model="formData.birthday"
          type="date"
          value-format="x"
          placeholder="选择出生日期"
          class="!w-240px"
        /> -->
        <div class="flex">
          <el-date-picker
            v-model="formData.year"
            value-format="YYYY"
            type="year"
            placeholder="年"
            class="w-90px!"
          />

          <el-select v-model="formData.month" placeholder="月" class="ml-10px w-90px!">
            <el-option key="1" label="1月" value="01" />
            <el-option key="2" label="2月" value="02" />
            <el-option key="3" label="3月" value="03" />
            <el-option key="4" label="4月" value="04" />
            <el-option key="5" label="5月" value="05" />
            <el-option key="6" label="6月" value="06" />
            <el-option key="7" label="7月" value="07" />
            <el-option key="8" label="8月" value="08" />
            <el-option key="9" label="9月" value="09" />
            <el-option key="10" label="10月" value="10" />
            <el-option key="11" label="11月" value="11" />
            <el-option key="12" label="12月" value="12" />
          </el-select>
          <el-select v-model="formData.day" placeholder="日" class="ml-10px w-90px!">
            <el-option key="1" label="1日" value="01" />
            <el-option key="2" label="2日" value="02" />
            <el-option key="3" label="3日" value="03" />
            <el-option key="4" label="4日" value="04" />
            <el-option key="5" label="5日" value="05" />
            <el-option key="6" label="6日" value="06" />
            <el-option key="7" label="7日" value="07" />
            <el-option key="8" label="8日" value="08" />
            <el-option key="9" label="9日" value="09" />
            <el-option key="10" label="10日" value="10" />
            <el-option key="11" label="11日" value="11" />
            <el-option key="12" label="12日" value="12" />
            <el-option key="13" label="13日" value="13" />
            <el-option key="14" label="14日" value="14" />
            <el-option key="15" label="15日" value="15" />
            <el-option key="16" label="16日" value="16" />
            <el-option key="17" label="17日" value="17" />
            <el-option key="18" label="18日" value="18" />
            <el-option key="19" label="19日" value="19" />
            <el-option key="20" label="20日" value="20" />
            <el-option key="21" label="21日" value="21" />
            <el-option key="22" label="22日" value="22" />
            <el-option key="23" label="23日" value="23" />
            <el-option key="24" label="24日" value="24" />
            <el-option key="25" label="25日" value="25" />
            <el-option key="26" label="26日" value="26" />
            <el-option key="27" label="27日" value="27" />
            <el-option key="28" label="28日" value="28" />
            <el-option key="29" label="29日" value="29" />
            <el-option key="30" label="30日" value="30" />
            <el-option key="31" label="31日" value="31" />
          </el-select>
          <el-checkbox class="pl-15px" v-model="formData.isLunar"
            ><span class="font16">农历</span>
          </el-checkbox></div
        >
      </el-form-item>
      <el-form-item label="身高" prop="height">
        <el-input-number
          v-model="formData.height"
          class="!w-240px"
          :precision="2"
          :controls="false"
        >
          <template #suffix>
            <span>CM</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="当前体重" prop="weight">
        <el-input-number
          v-model="formData.weight"
          class="!w-240px"
          :precision="2"
          :controls="false"
        >
          <template #suffix>
            <span>KG</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="目标体重" prop="targetWeight">
        <el-input-number
          v-model="formData.targetWeight"
          class="!w-240px"
          :precision="2"
          :controls="false"
        >
          <template #suffix>
            <span>KG</span>
          </template>
        </el-input-number>
      </el-form-item>

      <!-- <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->

      <!-- <el-form-item label="头像" prop="avatar">
        <UploadImg v-model="formData.avatar" :limit="1" :is-show-tip="false" />
      </el-form-item> -->

      <!-- <el-form-item label="所在地" prop="areaId">
        <el-tree-select
          v-model="formData.areaId"
          :data="areaList"
          :props="defaultProps"
          :render-after-expand="true"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="客户来源" prop="source">
        <el-select v-model="formData.source" class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐人">
        <el-select
          v-model="formData.spreadId"
          class="!w-240px"
          filterable
          placeholder="选择或搜索推荐人"
        >
          <el-option
            v-for="item in memberList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          >
            <span>{{ item.nickname }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="归属员工" prop="employeeId">
        <el-select
          v-model="formData.employeeId"
          placeholder="请选择归属员工"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in employeeList"
            :key="item.employeeId"
            :label="item.employeeName"
            :value="item.employeeId"
          >
            <span>{{ item.employeeName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户标签" prop="tagIds">
        <MemberTagSelect v-model="formData.tagIds" show-add />
      </el-form-item>
      <el-form-item label="用户分组" prop="groupId">
        <MemberGroupSelect v-model="formData.groupId" />
      </el-form-item>
      <el-form-item label="消费密码" prop="password" v-if="formData.id == undefined">
        <el-input
          v-model="formData.password"
          maxlength="6"
          show-password
          autocomplete="new-password"
          type="password"
          :formatter="formatterCode"
          placeholder="请输入6位纯数字密码"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword" v-if="formData.id == undefined">
        <el-input
          v-model="formData.checkPassword"
          maxlength="6"
          show-password
          autocomplete="new-password"
          type="password"
          :formatter="formatterCode"
          placeholder="请输入6位纯数字密码"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设为推广人">
        <el-switch v-model="formData.spreadEnable" />
      </el-form-item>
      <el-form-item label="会员备注" prop="mark">
        <el-input
          type="textarea"
          v-model="formData.mark"
          class="!w-240px"
          placeholder="请输入会员备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/member/user'
import * as AreaApi from '@/api/system/area'
import * as ShopUserApi from '@/api/shop/system/user/index'

import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import { verifiyDigitalCode } from '@/utils/formatter'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  mobile: undefined,
  password: undefined,
  status: 1,
  nickname: undefined,
  avatar: undefined,
  name: undefined,
  sex: 1,
  areaId: undefined,
  birthday: undefined,
  mark: undefined,
  tagIds: [],
  groupId: undefined,
  weight: undefined,
  targetWeight: undefined,
  height: undefined,
  isLunar: false,
  employee: undefined,

  employeeId: undefined,
  year: undefined,
  month: undefined,
  day: undefined,
  source: undefined,
  spreadId: undefined,
  spreadName: undefined,
  spreadEnable: false,
  checkPassword: undefined
})

const equalToPassword = (rule, value, callback) => {
  if (formData.value.password !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const formRules = reactive({
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: t('profile.rules.truephone'),
      trigger: 'blur'
    }
  ],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  checkPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref
const areaList = ref([]) // 地区列表
const formatterCode = (value: string) => {
  return verifiyDigitalCode(value)
}
const employeeList = ref<any>([]) //员工列表
const memberList = ref<any>([]) //会员列表
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  employeeList.value = await ShopUserApi.getEmployeeList()
  const memberData = await UserApi.getUserPage({})
  memberList.value = memberData.list
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as any
    if (data.spreadId) {
      data.spreadName = memberList.value.find((item) => {
        return item.id == data.spreadId
      }).nickname
    }
    if (data.employeeId) {
      data.employee = employeeList.value.find((item) => {
        return item.employeeId == data.employeeId
      }).employeeName
    }
    if (formType.value === 'create') {
      // 说明：目前暂时没有新增操作。如果自己业务需要，可以进行扩展
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mobile: undefined,
    password: undefined,
    status: 1,
    nickname: undefined,
    avatar: undefined,
    name: undefined,
    targetWeight: undefined,
    sex: 1,
    areaId: undefined,
    birthday: undefined,
    mark: undefined,
    tagIds: [],
    groupId: undefined,
    weight: undefined,
    height: undefined,
    isLunar: false,
    employee: undefined,
    employeeId: undefined,
    year: undefined,
    month: undefined,
    day: undefined,
    source: undefined,
    spreadId: undefined,
    spreadName: undefined,
    spreadEnable: false,
    checkPassword: undefined
  }
  formRef.value?.resetFields()
}
</script>
